package com.live.dengdengtv.activity.support;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.Interpolator;
import android.widget.ImageView;
import android.widget.TextView;

import com.live.dengdengtv.R;
import com.live.dengdengtv.activity.live.LiveingActivity;
import com.live.dengdengtv.view.CircleImageView;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.LinkedBlockingQueue;

import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;

/**
 *
 * 循环使用显示礼物的布局, new新的view然后addView模式不建议使用,耗时,耗内存
 * Created by wyf on 2016/9/28.
 */
public class GiftShowManager {
    private final static int SHOW_GIFT_FLAG = 1;//显示礼物
    private final static int SHOW_CONTINUE_GIFT_FLAG = 2;//显示礼物


    private final static int LOOP_TIME = 1000;//轮询时间

    private static List<Gift> giftList = new ArrayList<Gift>();

    private LinkedBlockingQueue<Gift> giftQueue;//礼物的队列
    private List<View> layoutGift;

    //空闲的 显示礼物的View队列.  使用集合,在于便于扩展更多显示礼物的view,通常只用两行显示礼物
    private LinkedBlockingQueue<View> availableView = new LinkedBlockingQueue<View>(10);


    private LiveingActivity liveingActivity;

    private GifImageView mGifImageView;
    private TextView mVirTicket_tv;

    /**
     *
     * @param activity
     * @param layoutGift        普通礼品View
     * @param gifImageView      gif动画
     * @param virTicket_tv      虚拟券
     */
    public GiftShowManager(LiveingActivity activity, List<View> layoutGift,GifImageView gifImageView,TextView virTicket_tv){
        this.liveingActivity = activity;
        this.giftQueue = new LinkedBlockingQueue<Gift>(100);
        this.layoutGift = layoutGift;
        this.mGifImageView = gifImageView;
        this.mVirTicket_tv = virTicket_tv;
        initAnim(activity, layoutGift);

    }

    private void initAnim(Context context, List<View> layoutGift) {
        for(View giftCell : layoutGift){

            AnimationSet animIn = (AnimationSet) AnimationUtils.loadAnimation(context, R.anim.gift_left_in);
            AnimationSet animOut = (AnimationSet) AnimationUtils.loadAnimation(context, R.anim.gift_up_out);
            AnimationSet animNum = (AnimationSet) AnimationUtils.loadAnimation(context, R.anim.gift_num_setv2);
            animNum.setInterpolator(new NumInterpolator());
            giftCell.setTag(R.id.animIn, animIn);
            giftCell.setTag(R.id.animNum, animNum);
            giftCell.setTag(R.id.animOut, animOut);
            this.availableView.add(giftCell);

        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                   case SHOW_GIFT_FLAG:
                    showGiftAnimation((Gift) msg.obj);
                    break;
//                   case SHOW_CONTINUE_GIFT_FLAG:
//                    showContinueGiftAnimation((View) msg.obj);
//                    break;
                   case 5:
                       Aniobj  aniobj = (Aniobj) msg.obj;
//                       Log.e("handleMessage",(num_tv.getAnimation() == null)+"");
                       Log.e("handleMessage","ttt");

                       aniobj.num_tv.startAnimation(aniobj.animation);
                       break;
                }
            }
    };


    public void showGifView(Gift gift) {

        try {
            mGifImageView.setVisibility(View.VISIBLE);
            GifDrawable gifDrawable = new GifDrawable(liveingActivity.getResources(), gift.gifResId);
            // gif1加载一个动态图gif
            mGifImageView.setImageDrawable(gifDrawable);

            int duration = gifDrawable.getDuration();
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    mGifImageView.setImageDrawable(null);
                    mGifImageView.setVisibility(View.GONE);
                }
            },duration);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void showGiftAnimation(Gift gift){
        //如果是主播,增加虚拟券
//        if(CurLiveInfo.getIdStatus() == Constants.HOST){
//            LoginInfo.getInstance().addVirTicket(gift.giftValue);
//        }
        CurLiveInfo.addVirTicket(gift.giftValue);
        mVirTicket_tv.setText(CurLiveInfo.getVirTicket()+"");//增加主播虚拟券


        if (!gift.continued && gift.gifResId != 0) {
            showGifView(gift);
        }

        final View giftCell = availableView.poll();
        giftCell.setTag(R.id.gift, gift);
        giftCell.setVisibility(View.VISIBLE);

        CircleImageView head_iv = (CircleImageView) giftCell.findViewById(R.id.head_iv);
        TextView name_tv = (TextView) giftCell.findViewById(R.id.name_tv);
        TextView msg_tv = (TextView) giftCell.findViewById(R.id.msg_tv);
        ImageView gift_imageView = (ImageView) giftCell.findViewById(R.id.gift_imageView);
        TextView num_tv = (TextView) giftCell.findViewById(R.id.num_tv);

        gift.hasShowNum++;
        num_tv.setText("X "+gift.num);
        msg_tv.setText(gift.giftName);
        gift_imageView.setImageResource(gift.imageResId);

        AnimationSet animIn = (AnimationSet) giftCell.getTag(R.id.animIn);
        AnimationSet animNum = (AnimationSet) giftCell.getTag(R.id.animNum);
        final AnimationSet animOut = (AnimationSet) giftCell.getTag(R.id.animOut);

        giftCell.startAnimation(animIn);
        num_tv.startAnimation(animNum);

        animNum.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) { }
            @Override
            public void onAnimationEnd(Animation animation) {

                String contin = (String) giftCell.getTag(R.id.contin);
                Gift gift = (Gift) giftCell.getTag(R.id.gift);

                Log.e("onAnimationEnd","Num:"+ gift.num + " hasShowNum:"+ gift.hasShowNum+"  "+ SystemClock.elapsedRealtime());

                if(gift.hasShowNum < gift.num){
                    Log.e("onAnimationEnd","startAnimation: animNum"+"  "+ SystemClock.elapsedRealtime());

                    TextView num_tv = (TextView) giftCell.findViewById(R.id.num_tv);
                    gift.hasShowNum++;
                    num_tv.setText("X "+gift.num);
//                    animation.reset();
//                    num_tv.startAnimation(animation);

                    Aniobj aniobj = new Aniobj();
                    aniobj.animation = animation;
                    aniobj.num_tv = num_tv;

                    Message msg = new Message();
                    msg.what = 5;
                    msg.obj = aniobj;
                    handler.sendMessageDelayed(msg,5);

//                    Log.e("onAnimationEnd","animNum:"+ gift.num);
                }else {
                    giftCell.startAnimation(animOut);
                    Log.e("onAnimationEnd","startAnimation: animOut"+"  "+ SystemClock.elapsedRealtime());
                }
            }
            @Override
            public void onAnimationRepeat(Animation animation) { }
        });
        animOut.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) { }
            @Override
            public void onAnimationEnd(Animation animation) {
                Gift gift = (Gift) giftCell.getTag(R.id.gift);
                gift.num = 0;
                gift.hasShowNum = 0;
                giftCell.setVisibility(View.INVISIBLE);
                availableView.add(giftCell);
            }
            @Override
            public void onAnimationRepeat(Animation animation) { }
        });
    }

    private static class Aniobj{
        TextView num_tv;
        Animation animation;
    }

    //使用子线程轮询---使用handler耗费主线程
    private Timer timer = new Timer();
    private TimerTask task = new TimerTask() {
        @Override
        public void run() {

            for (View giftCell : layoutGift){
                if(giftCell.getVisibility() == View.VISIBLE){
                    Gift gift1 = giftQueue.peek();
                    Gift gift2 = (Gift) giftCell.getTag(R.id.gift);
                    if(gift1!=null && gift2!=null && gift1.continued && gift1.id.equals(gift2.id)&& gift1.senderId.equals(gift2.senderId)){

                        AnimationSet animNum = (AnimationSet) giftCell.getTag(R.id.animNum);
                        AnimationSet animOut = (AnimationSet) giftCell.getTag(R.id.animOut);
//                        animNum.setAnimationListener(null);
//                        animOut.setAnimationListener(null);

                        gift1.num++;
//                        giftCell.setTag(R.id.contin,"true");

//                        Message msg = new Message();
//                        msg.what = SHOW_CONTINUE_GIFT_FLAG;
                        giftQueue.remove(gift1);
//                        msg.obj = giftCell;
//                        handler.sendMessage(msg);
                        Log.e("run()","contin"+"  "+ SystemClock.elapsedRealtime());
                        return;
                    }
                }
            }

            if(availableView.size() != 0){
                Gift gift = giftQueue.poll();
                if(gift != null){
                    gift.num++;
                    Message msg = new Message();
                    msg.what = SHOW_GIFT_FLAG;
                    msg.obj = gift;
                    handler.sendMessage(msg);
                    Log.e("run()","fist"+"  "+ SystemClock.elapsedRealtime());
                }
            }
        }
    };
    //开始显示礼物
    public void startGift() {
        if(giftList.size() == 0){
            getData();
        }

        timer.schedule(task, 2000, LOOP_TIME);
    }

    public void stop(){
        timer.cancel();

        giftQueue.clear();

        liveingActivity = null;
    }

    public List<Gift> getGiftList(){
        return giftList;
    }

    public void addGift(Gift gift){
        giftQueue.add(gift);
    }
    public void addGift(String giftId ,String senderId){
        for (Gift gift: giftList){
            if(gift.id.equals(giftId)){
                gift.senderId = senderId;
                giftQueue.add(gift);
                return;
            }
        }
    }
    public static Gift getGift(String giftId){
        if(giftList.size() == 0){
            getData();
        }

        for (Gift gift: giftList){
            if(gift.id.equals(giftId)){
                return gift;
            }
        }
        return null;
    }

    public static class Gift{
        public String id;
        public String senderId;
        public String userName;
        public String userFaceUrl;
        public int imageResId;
        public int gifResId = 0;
        public boolean continued = true;
        public String giftName;
        public String giftValue;
        public int num = 0;
        public int hasShowNum = 0;
    }

    public static class NumInterpolator implements Interpolator{

        @Override
        public float getInterpolation(float input) {
            return myInterpolation(input, 1.0F, 0.3F);
        }

        private float myInterpolation(float input, float parama, float paramb) {

            if (input == 0.0F)
                return 0.0F;

            if (input >= 1.0F) {
                return 1.0F;
            }

            return (float) (1.0D + parama * Math.pow(2.0D, -10.0F * input) * Math.sin(6.283185307179586D * input / paramb));
        }
    }
    private static void getData(){
        giftList.clear();

        Gift gift;

        gift = new Gift();
        gift.continued = true;
        gift.imageResId = R.mipmap.gift_111;
        gift.id = "1";
        gift.giftName = "小红花";
        gift.giftValue = "1";
        giftList.add(gift);
        gift = new Gift();
        gift.continued = true;
        gift.imageResId = R.mipmap.gift_112;
        gift.id = "2";
        gift.giftName = "小气球";
        gift.giftValue = "3";
        giftList.add(gift);
        gift = new Gift();
        gift.continued = true;
        gift.imageResId = R.mipmap.gift_113;
        gift.id = "3";
        gift.giftName = "小红旗";
        gift.giftValue = "5";
        giftList.add(gift);
        gift = new Gift();
        gift.continued = true;
        gift.imageResId = R.mipmap.gift_114;
        gift.id = "4";
        gift.giftName = "小红鸟";
        gift.giftValue = "10";
        giftList.add(gift);

        gift = new Gift();
        gift.continued = false;
        gift.imageResId = R.mipmap.gift_121;
        gift.gifResId = R.drawable.gift_porsche;
        gift.id = "5";
        gift.giftName = "保时捷";
        gift.giftValue = "1200";
        giftList.add(gift);
        gift = new Gift();
        gift.continued = false;
        gift.imageResId = R.mipmap.gift_122;
        gift.gifResId = R.drawable.gift_plane;
        gift.id = "6";
        gift.giftName = "大灰机";
        gift.giftValue = "2600";
        giftList.add(gift);
        gift = new Gift();
        gift.continued = false;
        gift.imageResId = R.mipmap.gift_123;
        gift.gifResId = R.drawable.gift_ferrari;
        gift.id = "7";
        gift.giftName = "法拉利";
        gift.giftValue = "6666";
        giftList.add(gift);
        gift = new Gift();
        gift.continued = false;
        gift.imageResId = R.mipmap.gift_124;
        gift.gifResId = R.drawable.gift_ship;
        gift.id = "8";
        gift.giftName = "爱情巨轮";
        gift.giftValue = "13140";
        giftList.add(gift);

        gift = new Gift();
        gift.continued = true;
        gift.imageResId = R.mipmap.gift_211;
        gift.id = "9";
        gift.giftName = "爱你";
        gift.giftValue = "20";
        giftList.add(gift);
        gift = new Gift();
        gift.continued = true;
        gift.imageResId = R.mipmap.gift_212;
        gift.id = "10";
        gift.giftName = "小风扇";
        gift.giftValue = "1";
        giftList.add(gift);
        gift = new Gift();
        gift.continued = true;
        gift.imageResId = R.mipmap.gift_213;
        gift.id = "11";
        gift.giftName = "棒棒糖";
        gift.giftValue = "1";
        giftList.add(gift);
        gift = new Gift();
        gift.continued = true;
        gift.imageResId = R.mipmap.gift_214;
        gift.id = "12";
        gift.giftName = "麦克风";
        gift.giftValue = "2";
        giftList.add(gift);

        gift = new Gift();
        gift.continued = false;
        gift.imageResId = R.mipmap.gift_221;
        gift.id = "13";
        gift.giftName = "皇冠";
        gift.giftValue = "500";
        giftList.add(gift);
        gift = new Gift();
        gift.continued = false;
        gift.imageResId = R.mipmap.gift_222;
        gift.id = "14";
        gift.giftName = "一生一世";
        gift.giftValue = "1314";
        giftList.add(gift);
        gift = new Gift();
        gift.continued = false;
        gift.imageResId = R.mipmap.gift_223;
        gift.gifResId = R.drawable.gift_lamborghini;
        gift.id = "15";
        gift.giftName = "兰博基尼";
        gift.giftValue = "2600";
        giftList.add(gift);
        gift = new Gift();
        gift.continued = false;
        gift.imageResId = R.mipmap.gift_224;
        gift.gifResId = R.drawable.gift_fireworks;
        gift.id = "16";
        gift.giftName = "礼花";
        gift.giftValue = "6666";
        giftList.add(gift);


        gift = new Gift();
        gift.continued = true;
        gift.imageResId = R.mipmap.gift_311;
        gift.id = "17";
        gift.giftName = "扑克牌";
        gift.giftValue = "5";
        giftList.add(gift);
        gift = new Gift();
        gift.continued = true;
        gift.imageResId = R.mipmap.gift_312;
        gift.id = "18";
        gift.giftName = "杯子";
        gift.giftValue = "10";
        giftList.add(gift);
        gift = new Gift();
        gift.continued = true;
        gift.imageResId = R.mipmap.gift_313;
        gift.id = "19";
        gift.giftName = "啤酒";
        gift.giftValue = "1";
        giftList.add(gift);
        gift = new Gift();
        gift.continued = true;
        gift.imageResId = R.mipmap.gift_314;
        gift.id = "20";
        gift.giftName = "甜甜圈";
        gift.giftValue = "88";
        giftList.add(gift);

        gift = new Gift();
        gift.continued = false;
        gift.imageResId = R.mipmap.gift_321;
        gift.id = "21";
        gift.giftName = "冰激凌";
        gift.giftValue = "500";
        giftList.add(gift);
        gift = new Gift();
        gift.continued = true;
        gift.imageResId = R.mipmap.gift_322;
        gift.id = "22";
        gift.giftName = "泰迪熊";
        gift.giftValue = "100";
        giftList.add(gift);
        gift = new Gift();
        gift.continued = true;
        gift.imageResId = R.mipmap.gift_323;
        gift.id = "23";
        gift.giftName = "么么哒";
        gift.giftValue = "188";
        giftList.add(gift);
        gift = new Gift();
        gift.continued = true;
        gift.imageResId = R.mipmap.gift_324;
        gift.id = "24";
        gift.giftName = "拖鞋";
        gift.giftValue = "200";
        giftList.add(gift);
    }
}
